<template>
  <div class="main-page">
    <div class="main-01">
      <div class="main-tab-01-01" style="height:350px">
        <div class="main-tab-title" style="margin-bottom: 0;">
          <span>学生概括</span>
        </div>
        <div class="main-tab-box">
          <div class="main-tab-box-l">
            <img src="./assets/img/h-10.png" class="main-tab-box-l-img"/>
            <div class="main-tab-box-t">
              <div class="main-tab-box-t-01">
                <span>学生总数</span>
                <span class="color-t03">{{ student.count || 0 }}</span>
              </div>
            </div>
          </div>
          <div class="main-tab-box-l">
            <img src="./assets/img/h-006.png" class="main-tab-box-l-img"/>
            <div class="main-tab-box-t">
              <div class="main-tab-box-t-01">
                <span>性别</span>
                <span class="color-t03">男</span>
              </div>
              <div class="main-tab-box-t-01">
                <span>人数</span>
                <span class="color-t02">{{
                    student.boy || 0
                  }}
                </span>
              </div>
              <div class="main-tab-box-t-01">
                <span>占比</span>
                <span class="color-t02">
                   {{ ((student.boy / student.count) * 100).toFixed(1) }}%
                </span>
              </div>
            </div>
          </div>
          <div class="main-tab-box-l">
            <img src="./assets/img/h-10.png" class="main-tab-box-l-img"/>
            <div class="main-tab-box-t">
              <div class="main-tab-box-t-01">
                <span>性别</span>
                <span class="color-t03">女</span>
              </div>
              <div class="main-tab-box-t-01">
                <span>人数</span>
                <span class="color-t02">
                  {{
                    student.girl || 0
                  }}

                </span>
              </div>
              <div class="main-tab-box-t-01">
                <span>占比</span>
                <span class="color-t02">{{ ((student.girl / student.count) * 100).toFixed(1) }}% </span>
              </div>
            </div>
          </div>
          <div class="main-tab-box-l">
            <img src="./assets/img/h-11.png" class="main-tab-box-l-img"/>
            <div class="main-tab-box-t">
              <div class="main-tab-box-t-01">
                <span >班级总数：</span>
                <span class="color-t02">{{student.class || 0}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>学生分布</span>
        </div>
        <div id="studentDistributionChart" style="width:100%;height: 400px;" class="echartMap-line"></div>
      </div>
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>教具采购（套、件）</span>
        </div>
        <div id="teachingAidsChart" style="width:100%;height: 400px;" class="echartMap-line"></div>
      </div>
    </div>
    <div class="main-02">
      <div class="main-02-top" style="height: 870px">
        <div class="dropdown-container-box">
          班级：
          <select v-model="selectId" @change="changClass($event)" placeholder="年段">
            <option value="" disabled selected style="color: white;">请选择</option>
            <option v-for="item in selectList" :value="item.id" :key="item.id">{{ item.section_name }}</option>
          </select>
          <select v-model="classId" @change="changClassSel($event)" placeholder="班级">
            <option value="" disabled selected style="color: white;">请选择</option>
            <option v-for="item in classList" :value="item.id" :key="item.id">{{ item.class_name }}</option>
          </select>
          学生：
          <input type="text " v-model="studentName" placeholder="学生姓名">
          <div class="dropdown-btn" @click="searchBox()">
            查询
          </div>
          <div class="dropdown-btn" @click="resectFn()">
            重置
          </div>
        </div>
        <div class="dropdown-container" v-loading="loading"
             element-loading-text="加载中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.5)">
          <div class="dropdown-container-in" v-if="character.length">
            <div v-for="student in character" :key="student.id" class="chart-container-line">
              <div :id="`radarChart-${student.id}`" :style="{ width: '320px', height: '332px' }"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-02-bottom">
        <div class="main-02-bottom-l">
          <div class="main-tab-title">
            <span>书籍采购</span>
          </div>
          <div id="book" style="width:100%;height: 450px;" class="home_top_Development"></div>
        </div>
        <div class="main-02-bottom-l">
          <div class="main-tab-title">
            <span>实时区角</span>
          </div>
<!--          <div id="topicChart" style="width:100%;height: 400px;" class="echartMap-line"></div>-->
          <div id="pieChart-corner" :style="{ width: '100%', height: '400px' }"></div>
        </div>
      </div>
    </div>
    <div class="main-03">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>学生平均发展水平</span>
          <span class="more-list" @click="showCornerPopup=true">更多+</span>
        </div>
        <div v-for="corner in corners" :key="corner.id" class="chart-container">
          <div :id="`pieChart-${corner.id}`" :style="{ width: '356px', height: '400px' }"></div>
        </div>
      </div>
    </div>
    <!--    <popup :visible.sync="showPopup"></popup>-->
    <popupCorner :visible.sync="showCornerPopup"></popupCorner>
    <popupCornerList :visible.sync="showPopup" :cornerId="cornerId" :sectionId="sectionId" :cornerName="cornerName"
                     :sectionName="sectionName"></popupCornerList>
    <popupCornerStudent :visible.sync="showCornerStudentPopup" :cornerDetail="cornerDetail"></popupCornerStudent>
  </div>
</template>

<script>
import {development, schoolBrandDomain, cornerBrand} from "@/api/admin/school";
import popup from "./components/popup"
import popupCorner from "./components/popupCorner"
import popupCornerList from "@/fullscreen/components/popupCornerList";
import popupCornerStudent from "@/fullscreen/components/popupCornerStudent";
import api from "@/utils/api";

let echarts = require('echarts')

export default {
  name: "home",
  components: {popup, popupCorner, popupCornerList, popupCornerStudent},
  data() {
    return {
      student: [],
      character: [],
      corners: [],
      showPopup: false,
      showCornerPopup: false,
      showCornerListPopup: false,
      cornerId: 0,
      cornerName: '',
      sectionId: 0,
      sectionName: '',
      classList: [],
      selectList: [],
      studentName: '',
      classId: '',
      selectId: '',
      loading: true,
      showCornerStudentPopup: false,
      cornerDetail: null
    }
  },
  created() {
    this.getSchoolFn();
    this.sectionInitFn()
    this.schoolBrandDomainFn()
    this.cornerBrandFn()
  },
  mounted() {
  },
  methods: {
    classInitFn() {
      this.$fetch(api.admin_classes_index, {
        p: 1,
        section_id: this.selectId
      }).then((response) => {
        console.log('response+++', response)
        this.classList = response.list.data
      }).catch((err) => {
        console.log(err)
      })
    },
    sectionInitFn() {
      this.$post(this.api.admin_section_index, {
        p: 1
      }).then((response) => {
        console.log('response++++', response)
        this.selectList = response.list.data
      }).catch((err) => {
        console.log(err)
      })
    },
    changClass(event) {
      console.log('event-changClass', event)
      console.log('selectId', this.selectId)
      this.classId = ''
      this.classInitFn()
    },
    changClassSel(event) {
      console.log('event-changClassSel', event)

    },
    searchBox() {
      if(!this.classId && !this.studentName){
        this.$message.warning('班级/姓名不能都为空');
        return
      }
      this.loading = true
      this.character = []
      this.schoolBrandDomainFn()
    },
    resectFn() {
      this.selectId = ''
      this.classId = ''
      this.classList = []
      this.studentName = ''
      this.loading = true
      this.character = []
      this.schoolBrandDomainFn()
    },
    schoolBrandDomainFn() {
      let that = this
      let data_ = {
        class_id: this.classId || undefined,
        name: this.studentName || undefined
      }
      schoolBrandDomain(data_).then(res => {
        this.character = res.list
        setTimeout(() => {
          for (let index in res.list) {
            let character = res.list[index]
            if (character && character.id) {
              that.initRadarChart(character, index);
            } else {
              console.error('Invalid character data:', character);
            }
          }
        }, 300)
      })
    },
    cornerBrandFn(){
      cornerBrand().then(res=>{
        console.log('实时去交+++++', res)
        this.initPieChartCorner(res)
      })
    },
    initPieChartCorner(corner) {
      let that = this
      const chartContainer = document.getElementById('pieChart-corner');
      const chart = echarts.init(chartContainer);
      const sections = corner.list.map(section => ({
        name: section.corner,
        cornerName: section.corner,
        id: section.id,
        value: section.use_number
      }));

      const option = {
        title: {
          text: `参与人数`,
          left: 'center',
          textStyle: {
            color: '#ddd' // 设置图例字体颜色为白色
          },
          show: false
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          show:false,
          textStyle: {
            color: '#ddd'
          }
        },
        series: [
          {
            name: '今日参与人数',
            type: 'pie',
            radius: '60%',
            data: sections
          }
        ]
      };

      chart.setOption(option);
      chart.on('click', function (params) {
        console.log('click', params);
        that.cornerDetail = params.data
        that.showCornerStudentPopup = true
      });
    },
    student_distribution_chart(data) {
      this.$nextTick(() => {
        const chartContainer = document.getElementById('studentDistributionChart');
        if (!chartContainer) {
          console.error('Element with id "studentDistributionChart" not found');
          return;
        }

        let chart = echarts.init(chartContainer);

        let option = {
          color: ['#3cd499'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: ['#315070'],
                type: 'dashed'
              }
            },
            data: data.map(item => item.section_name),
          },
          yAxis: {
            type: 'value',
            max: 200,
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#315070',
                type: 'dashed'
              }
            },
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: 0,
            top: '20px',
            containLabel: true
          },
          series: [{
            name: '人数',
            data: data.map(item => item.number),
            type: 'bar', // 将图表类型改为柱状图
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#b5c5d4',
                    fontSize: 16
                  }
                },
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    {offset: 0, color: 'white'}, // 白色
                    {offset: 1, color: '#3cd499'} // #3cd499
                  ]
                )
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(88, 88, 88, 0.1)'
            }
          }]
        };

        chart.setOption(option);
      });
    },
    //教具采购
    teaching_aids_chart(data) {
      this.$nextTick(() => {
        const chartContainer = document.getElementById('teachingAidsChart');
        if (!chartContainer) {
          console.error('Element with id "teachingAidsChart" not found');
          return;
        }

        let chart = echarts.init(chartContainer);

        // 计算总数
        const total = data.reduce((sum, item) => sum + item.number, 0);

        let option = {
          color: ['#1960b3'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          title: {
            text: `总数：${total}`,
            left: 'center', // 居中显示
            textStyle: {
              color: '#b5c5d4',
              fontSize: 16
            }
          },
          xAxis: {
            type: 'category',
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: ['#315070'],
                type: 'dashed'
              }
            },
            data: data.map(item => item.name),
          },
          yAxis: {
            type: 'value',
            max: 15000,
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#315070',
                type: 'dashed'
              }
            },
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: 0,
            top: '20px',
            containLabel: true
          },
          series: [{
            name: '套、件',
            data: data.map(item => item.number),
            type: 'bar', // 将图表类型改为柱状图
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#b5c5d4',
                    fontSize: 16
                  }
                },
                color: '#1960b3' // 设置柱状图的颜色
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(88, 88, 88, 0.1)'
            }
          }]
        };

        chart.setOption(option);
      });
    },

    topic_chart(data) {
      this.$nextTick(() => {
        const chartContainer = document.getElementById('topicChart');
        if (!chartContainer) {
          console.error('Element with id "topicChart" not found');
          return;
        }

        let chart = echarts.init(chartContainer);

        // 提取年份
        const years = data[0].year.map(year => year.name);

        // 提取每个等级的课题数据
        const seriesData = data.map(topic => ({
          name: topic.name,
          type: 'line',
          data: topic.year.map(year => year.number)
        }));

        let option = {
          color: ['#1960b3', '#ff7f50', '#87cefa', '#da70d6'], // 不同等级的颜色
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: data.map(topic => topic.name),
            textStyle: {
              color: 'white' // 设置图例字体颜色为白色
            }
          },
          xAxis: {
            type: 'category',
            data: years,
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: ['#315070'],
                type: 'dashed'
              }
            }
          },
          yAxis: {
            type: 'value',
            max: 50,
            min: 1,
            axisLine: {
              lineStyle: {
                color: '#b5c5d4'
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#315070',
                type: 'dashed'
              }
            }
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: 0,
            top: '20px',
            containLabel: true
          },
          series: seriesData
        };

        chart.setOption(option);
      });
    },
    async getSchoolFn() {
      try {
        const res = await development();
        if (res.code === 0) {
          this.student = res.student || [];
          // this.character = res.character || [];
          this.corners = res.corner || [];
          this.student_distribution_chart(res.section);
          this.teaching_aids_chart(res.tools);
          // this.topic_chart(res.topic);
          this.initBookChart(res.book);
          this.$nextTick(() => {
            // this.initializeCharts();
            this.initializeCornerCharts()
          });
        } else {
          console.error('API response code is not 0:', res);
        }
      } catch (error) {
        console.error('Error fetching school data:', error);
      }
    },
    initializeCharts() {
      if (this.character.length === 0) {
        // console.warn('No character data to initialize charts.');
        return;
      }
      // https://wyde.xmtranscend.cn/admin/school_brand/domain
      this.character.forEach(character => {
        if (character && character.id) {
          this.initRadarChart(character);
        } else {
          console.error('Invalid character data:', character);
        }
      });
    },
    initRadarChart(character, index) {
      // console.log(`Initializing radar chart for character: ${character.name}`); // 调试信息
      const chartId = `radarChart-${character.id}`;
      const chartContainer = document.getElementById(chartId);
      if (!chartContainer) {
        console.error(`Element with id "${chartId}" not found`);
        return;
      }

      const chart = echarts.init(chartContainer);

      // 提取指标名称和最大值
      const indicator = character.domain.map(domain => ({
        name: domain.name,
        max: 100
      }));

      // 提取每个领域的分数
      const values = character.domain.map(domain => domain.number);

      const option = {
        title: {
          text: `${character.name} - ${character.classes.class_name}`,
          left: 'center'
        },
        tooltip: {},
        radar: {
          indicator: indicator,
          shape: 'circle',
          center: ['50%', '50%'],
          radius: '70%',
          splitNumber: 5,
          axisName: {
            color: '#333'
          },
          splitArea: {
            areaStyle: {
              color: 'rgba(255, 255, 255, 0.2)'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#ccc'
            }
          }
        },
        series: [
          {
            name: '性格特征',
            type: 'radar',
            data: [
              {
                value: values,
                name: character.name,
                itemStyle: {
                  color: '#4fce7c'
                },
                areaStyle: {
                  color: 'rgba(79, 206, 124, 0.8)' // 设置填充颜色
                }
              }
            ]
          }
        ],
        backgroundColor: '#fff'
      };

      chart.setOption(option);
      if (this.character.length - 1 == index) {
        setTimeout(()=>{
          this.loading = false
        }, 400)
      }
    },
    initializeCornerCharts() {
      if (this.corners.length === 0) {
        console.warn('No corner data to initialize charts.');
        return;
      }

      this.corners.forEach(corner => {
        if (corner && corner.id) {
          this.initPieChart(corner);
        } else {
          console.error('Invalid corner data:', corner);
        }
      });
    },
    initPieChart(corner) {
      console.log(`Initializing pie chart for corner: ${corner.name}`); // 调试信息
      let that = this
      const chartId = `pieChart-${corner.id}`;
      const chartContainer = document.getElementById(chartId);
      if (!chartContainer) {
        console.error(`Element with id "${chartId}" not found`);
        return;
      }


      const chart = echarts.init(chartContainer);

      const sections = corner.section.map(section => ({
        name: section.section_name,
        cornerName: corner.name,
        id: section.id,
        value: section.number
      }));

      const option = {
        title: {
          text: `${corner.name} - 参加人数`,
          left: 'center',
          textStyle: {
            color: 'white' // 设置图例字体颜色为白色
          }
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '年段',
            type: 'pie',
            radius: '50%',
            data: sections,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      chart.setOption(option);
      chart.on('click', function (params) {
        console.log('click', params);
        that.cornerName = params.data.cornerName
        that.cornerId = corner.id
        that.sectionId = params.data.id
        that.sectionName = params.data.name
        that.showPopup = true
      });
    },
    // 书籍采购
    initBookChart(data) {
      // 处理数据
      const years = data.map(item => item.name);
      const teacherBooks = [];
      const studentBooks = [];

      data.forEach(item => {
        item.book.forEach(book => {
          if (book.name === '教师用书') {
            teacherBooks.push(book.number);
          } else if (book.name === '幼儿用书') {
            studentBooks.push(book.number);
          }
        });
      });

      // 计算总数
      const totalTeacherBooks = teacherBooks.reduce((sum, num) => sum + num, 0);
      const totalStudentBooks = studentBooks.reduce((sum, num) => sum + num, 0);

      // 初始化图表
      const chartDom = document.getElementById('book');
      const myChart = echarts.init(chartDom);

      // 设置图表选项
      const option = {
        title: {
          text: `教师用书 ${totalTeacherBooks}，幼儿用书 ${totalStudentBooks}`,
          left: 'center', // 居中显示
          textStyle: {
            color: '#b5c5d4',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: years
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '教师用书',
            type: 'bar',
            data: teacherBooks
          },
          {
            name: '幼儿用书',
            type: 'bar',
            data: studentBooks
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表
      myChart.setOption(option);
    }
  },
}
</script>

<style scoped>
.main-page {
  display: flex;
  padding: 10px;
}

.main-tab-title {
  background: url(./assets/img/h-008.png) no-repeat;
  background-size: 100% 50px;
  background-position: left bottom;
  height: 50px;
  font-style: italic;
  font-size: 26px;
  padding-left: 20px;
  line-height: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  display: flex;
  /*align-items: center;*/
}

.main-tab-title span {
  background: linear-gradient(to bottom, #fff, #fcfcb8);
  -webkit-background-clip: text; /* 将背景裁剪为文字区域 */
  -webkit-text-fill-color: transparent; /* 将文字颜色设置为透明 */
  /*color: #fcfcb8;*/
  /*text-shadow: 2px 2px 1px #000;*/
}

.main-tab-title span:first-child {
  flex: 1;
}

.color-t01 {
  color: #ffd93b;
}

.color-t02 {
  color: #32dcfb;
}

.color-t03 {
  color: #0fda83;
}

.main-01 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
}

.main-02 {
  flex: 1;
  background: rgba(5, 25, 53, .6);
  margin: 0 20px;
  border-radius: 10px;
}

.main-03 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
}

.main-tab-box {
  padding: 10px 0;
}

.main-tab-box-l {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.main-tab-box-l:last-child {
  margin-bottom: 0;
}

.main-tab-box-l-img {
  margin-right: 20px;
}

.main-tab-box-t {
  display: flex;
  align-items: center;
  flex: 1;
}

.main-tab-box-t-01 {
  flex: 1;
}

.main-tab-box-t-01 span:nth-child(1) {
  font-size: 14px;
  color: #ddd;
  margin-bottom: 5px;
  display: block;
}

.main-tab-box-t-01 span:nth-child(2) {
  font-size: 26px;
}

.home_top_Development {
  height: 100%;
  width: 100%;
}

.main-tab-01-01 {
  margin-bottom: 30px;
}

.main-02-bottom {
  display: flex;
  /*align-items: center;*/
  padding-top: 20px;
}

.main-02-bottom-l {
  flex: 1;
}

.main-02-bottom-l:first-child {
  margin-right: 20px;
}

.chart-container {
  display: inline-block;
  margin: 20px;
}

.banner-box img {
  width: 100%;
  display: block;
}

.main-02-top {
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.chart-container-line {
  margin-right: 15px;
  margin-bottom: 15px;
  display: inline-block;
}

.chart-container-line:nth-child(3n) {
  margin-right: 0;
}

.more-list {
  font-size: 16px;
  cursor: pointer;
}

.dropdown-container {
  flex: 1;
  overflow: hidden;
}

.dropdown-container-box {
  padding: 10px 0 20px;
  font-size: 24px;
  color: #fff;
  display: flex;
  align-items: center;
  /*height: 50px;*/
}

.dropdown-container-in {
  padding: 10px;
  overflow-y: auto;
  height: 100%;
}

.dropdown-container-box select {
  width: 180px;
  height: 50px;
  font-size: 24px;
  /*background: rgba(5, 25, 53, .6);*/
  color: #000;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 5px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"><path fill="%23ddd" d="M7 10l5 5 5-5z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 12px;
  margin-right: 10px;
}

.dropdown-container-box input {
  width: 150px;
  height: 50px;
  font-size: 24px;
  border-radius: 5px;
  padding-left: 10px;
}

.dropdown-container-box select:focus {
  outline: none;
}

.dropdown-btn {
  margin-left: 20px;
  border: 1px solid #fff;
  line-height: 48px;
  height: 50px;
  width: 120px;
  text-align: center;
  border-radius: 10px;
  cursor: pointer;
}

.dropdown-btn:hover {
  background: rgba(255, 255, 255, .4);
}
</style>
